<template>
  <div class="user">
    <!-- 就诊人管理模块 -->
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>就诊人管理</span>
          <el-button
            class="button"
            type="success"
            :icon="User"
            @click="addVisitor"
            v-if="scene === 0"
            >添加就诊人</el-button
          >
          <el-button
            class="button"
            type="danger"
            :icon="Delete"
            @click="cancelALlUser"
            v-if="scene === 1"
            >取消添加</el-button
          >
        </div>
      </template>
      <!-- 展示就诊人区域 -->
      <div class="user" v-if="scene === 0">
        <Visitor
          class="visitor"
          v-for="visitor in allUserArr"
          :key="visitor.id"
          :visitor="visitor"
          @changeScene="changeScene"
          @deleteVisitor = "deleteVisitor"
        ></Visitor>
      </div>
      <!-- 添加就诊人|修改就诊人区域 -->
      <div class="from" v-if="scene === 1">
        <el-divider content-position="left">就诊人信息</el-divider>
        <el-form style="width: 60%; margin: 10px auto" label-width="80px">
          <el-form-item label="用户姓名">
            <el-input placeholder="请输入用户姓名" v-model="userParams.name"></el-input>
          </el-form-item>
          <el-form-item label="证件类型">
            <el-select placeholder="请选择证件类型" v-model="userParams.certificatesType">
              <el-option v-for="(type) in typeArr" :key="type.id" :label="type.name" :value="type.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="证件号码">
            <el-input placeholder="请输入证件号码" v-model="userParams.certificatesNo"></el-input>
          </el-form-item>
          <el-form-item label="用户性别">
            <el-radio-group class="ml-4" v-model="userParams.sex">
              <el-radio label="1">男</el-radio>
              <el-radio label="0">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="出生日期">
            <el-date-picker type="datetime" placeholder="请选择出生日期" v-model="userParams.birthdate"  value-format="YYYY-MM-DD" />
          </el-form-item>
          <el-form-item label="手机号码">
            <el-input placeholder="请输入手机号码" v-model="userParams.phone"></el-input>
          </el-form-item>
        </el-form>

        <el-divider content-position="left">建档信息（完善部分医院首次就诊不排队建档）</el-divider>
        <el-form style="width: 60%; margin: 10px auto" label-width="80px">
          <el-form-item label="婚姻状况">
            <el-radio-group class="ml-4" v-model="userParams.isMarry">
              <el-radio label="1">已婚</el-radio>
              <el-radio label="0">未婚</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="自费/医保">
            <el-radio-group class="ml-4" v-model="userParams.isInsure">
              <el-radio label="1">自费</el-radio>
              <el-radio label="0">医保</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="当前住址">
             <el-cascader :props="props" v-model="userParams.addressSelected"/>
          </el-form-item>
          <el-form-item label="详细地址">
            <el-input placeholder="请输入详细地址" v-model="userParams.address"></el-input>
          </el-form-item>
        </el-form>

        <el-divider content-position="left">联系人信息（选填）</el-divider>
        <el-form style="width: 60%; margin: 10px auto" label-width="80px">
          <el-form-item label="用户姓名">
            <el-input placeholder="请输入用户姓名" v-model="userParams.contactsName"></el-input>
          </el-form-item>
          <el-form-item label="证件类型">
            <el-select placeholder="请选择证件类型" v-model="userParams.contactsCertificatesType">
              <el-option v-for="(type) in typeArr" :key="type.id" :label="type.name" :value="type.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="证件号码">
            <el-input placeholder="请输入证件号码" v-model="userParams.contactsCertificatesNo"></el-input>
          </el-form-item>
          <el-form-item label="手机号码">
            <el-input placeholder="请输入手机号码" v-model="userParams.contactsPhone"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submit">提交</el-button>
            <el-button @click="reset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, type CascaderProps } from 'element-plus'
import { User,Delete } from "@element-plus/icons-vue";
import { ref, onMounted, reactive,watch } from "vue";
// 引入API
import { reqAllUser,reqCertificatesType,reqCity,reqAddOrUpdateUser } from "@/api/user/index";
// 引入ts类型
import { allUserResponseData, AllUserArr,CertificatesTypeResponseData,CertificatesTypeArr,AddOrUpdateUserData,UserInfo } from "@/api/user/type";
// 引入路由器与路由
import { useRoute,useRouter } from 'vue-router';

// 获取路由器|路由对象
let router = useRouter();
let route = useRoute();
// 存储全部就诊人信息
let allUserArr = ref<AllUserArr>([]);
// 控制展示|添加或修改就诊人模块的切换
let scene = ref<number>(0);
// 存储证件类型
let typeArr = ref<CertificatesTypeArr>([])
// 收集就诊人表单信息
let userParams = reactive<AddOrUpdateUserData>({
    name: '',
    certificatesType: '',
    certificatesNo: '',
    sex: 0,
    birthdate: '',
    phone: '',
    isMarry: 0,
    isInsure:0,
    addressSelected: [],
    address:'',
    contactsName:'',
    contactsCertificatesType:'',
    contactsCertificatesNo:'',
    contactsPhone:''
})
const props: CascaderProps = {
  lazy: true,
  async lazyLoad(node:any, resolve:any) {
    // 获取城市信息
    let result:any = await reqCity(node.data.id || 86)
    // console.log(result);
    //整理数据
    let showData = result.data.map((item: any) => {
      return {
        id: item.id,
        label: item.name,
        value: item.value,
        leaf: !item.hasChildren,
      };
    });
    // 注入信息
    resolve(showData)
  },
}
// 组件挂载完毕获取全部就诊人信息
onMounted(() => {
  // 获取全部就诊人信息
  getAllUser();
  // 获取证件类型
  getAllType();
  // 判断路由
  if(route.query.type === 'add'){
    scene.value = 1
  }
  if(route.query.type === 'edit'){
    scene.value = 1
  }
});
// 监听userArr
watch(()=>allUserArr.value,()=>{
  if(route.query.type == 'edit'){
    let user = allUserArr.value.find((item:any)=>{
      return item.id == route.query.id
    })
    Object.assign(userParams,user)
  }
})
// 封装一个方法获取全部就诊人信息
const getAllUser = async () => {
  const result: allUserResponseData = await reqAllUser();
  if (result.code == 200) {
    // 存储全部就诊人信息
    allUserArr.value = result.data;
  }
};
// 添加就诊人按钮的回调
const addVisitor = () => {
  // 添加之前要清空上一次的数据
  reset();
  // 切换为添加就诊人模块
  scene.value = 1;
};
// 取消添加就诊人的回调
const cancelALlUser = ()=>{
  scene.value = 0
  // 清空上一次的数据
  reset();
}
// 就诊人管理子组件的自定义事件回调
const changeScene = (user:UserInfo) => {
  scene.value = 1;
  // 修改就诊人信息
  Object.assign(userParams,user)
};
// 获取证件类型的回调
const getAllType = async ()=>{
  const result:CertificatesTypeResponseData = await reqCertificatesType();
  if(result.code == 200){
    typeArr.value = result.data
  }
}
// 点击提交按钮的回调
const submit = async ()=>{
  try{
    // 发送提交请求
    await reqAddOrUpdateUser(userParams);
    // 提示信息
    ElMessage({
      type:'success',
      message:userParams.id?'更新成功':'添加成功'
    })
    // 判断路由
    if(route.query.type === 'add'){
      router.back();
    }else{
      // 切换场景值
      scene.value = 0
    }
    // 重新获取全部就诊人信息
    getAllUser();
  }catch(err){
    ElMessage({
      type:'error',
      message:userParams.id?'更新失败':'添加失败'
    })
  }
}
// 重置按钮的回调
const reset = ()=>{
  Object.assign(userParams,{
    id:null,
    name: '',
    certificatesType: '',
    certificatesNo: '',
    sex: 0,
    birthdate: '',
    phone: '',
    isMarry: 0,
    isInsure:0,
    addressSelected: [],
    address:'',
    contactsName:'',
    contactsCertificatesType:'',
    contactsCertificatesNo:'',
    contactsPhone:''
})
}
// 给子组件删除按钮的自定义事件
const deleteVisitor = ()=>{
  // 重新获取全部就诊人信息
  getAllUser();
}
</script>

<style scoped lang="scss">
.user{
  margin-top: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.user {
  display: flex;
  flex-wrap: wrap;

  .visitor {
    width: 31%;
    margin: 10px;
  }
}
</style>